package com.itcs.app.itcapi;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itcs.app.util.ParamMap;
import com.itcs.trading.mapper.UserInfoMapper;
import com.itcs.trading.model.UserInfo;

/**
 * 验证请求合法性
 * @author Administrator
 * @date 2018-04-09 15:10
 *
 */
@WebFilter(urlPatterns = "/*", filterName = "ITCWebFilter")
public class ITCWebFilter implements Filter{
	
	private static final Logger logger = LoggerFactory.getLogger(ITCWebFilter.class);
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		boolean flag = checkUser(httpRequest);
		if (flag) {
			 chain.doFilter(request, response);
		} else {
			HttpServletResponse httpresponse = (HttpServletResponse)response;
			httpresponse.setCharacterEncoding("utf-8");
			httpresponse.getWriter().print("请先登录");
//			httpresponse.sendRedirect("/app/pages/login.html");
		}
	}

	@Override
	public void destroy() {
		
	}
	
	private boolean checkUser(HttpServletRequest request) {
		/*String userId = null;
		userId = request.getParameter("userId");
		if (userId == null) {
			userId = request.getParameter("id");
		}
		if (userId == null) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
				StringBuffer sb = new StringBuffer("");
				String temp = "";
				while ((temp = br.readLine()) != null) {
					sb.append(temp);
				}
				br.close();
				JSONObject jsonObject = (JSONObject)JSONObject.parse(sb.toString());
				userId = jsonObject.getString("userId");
				if (userId == null) {
					userId = jsonObject.getString("id");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/
		ParamMap param = ParamMap.init(request);
		logger.info("=========="+param.toString());
		String userId = (String)param.get("userId");
		if (userId == null || "".equals(userId)) {
			return false;
		}
		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		UserInfoMapper userInfoMapper = (UserInfoMapper)factory.getBean("userInfoMapper");
		
		UserInfo user = userInfoMapper.selectByPrimaryKey(Long.valueOf(userId));
		if (user != null) {
			return true;
		}
		return false;
	}
}
